//
//  SMRTAgencyListViewController.m
//  SMRTv1
//
//  Created by Ding on 8/9/13.
//  Copyright (c) 2013 Trans-Intelligence. All rights reserved.
//

#import "SMRTAgencyListViewController.h"

@interface SMRTAgencyListViewController ()

@end

@implementation SMRTAgencyListViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_agencyNameSection release];
    [_agencySection release];
    [_assistingToolsSection release];
    [_addAgencyButton release];
    [_agencyList release];
    [_imageView release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [XMLParser loadDataXML];
    //    self.tableView.backgroundColor = [UIColor colorWithRed:0 green:0.18 blue:0.384 alpha:1];
    self.tableView.backgroundColor = [UIColor clearColor];    
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
//    UIImageView *unrLogoImageView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UNRLogo.png"]] autorelease];
//    unrLogoImageView.frame=CGRectMake(60, 10, 160, 50);
//    [self.tableView addSubview:unrLogoImageView];
    
    UIImageView *nameImageView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Name2.png"]] autorelease];
    nameImageView.frame=CGRectMake(10, 10, 300, 50);
    [self.tableView addSubview:nameImageView];

    if (!_agencyNameSection) {
        _agencyNameSection=[[TableSection alloc]init];
        _agencyNameSection.header=@"   \n  \n   ";
    }
    if(!_agencySection)
    {
        _agencySection=[[TableSection alloc]init];
        self.agencyList=[XMLParser getAgencyList];
        _agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.agencyList.count; i++) {
            [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
        }
        
        _agencySection.header=@"Agency List";
    }
    
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:_agencyNameSection];
        [_sections addObject:_agencySection];
    }

    if (!_imageView) {
        _imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_title.png"]];
    }    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *configurationItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"Setting-icon.png"] target:self action:@selector(goToDataFileSelection:)] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: space,configurationItem,nil ];
}

//- (void)viewDidUnload
//{
//    [super viewDidUnload];
//    // Release any retained subviews of the main view.
//    // e.g. self.myOutlet = nil;
//    self.sections=nil;
//    self.agencyNameSection=nil;
//    self.agencySection=nil;
//    self.assistingToolsSection=nil;
//    self.addAgencyButton=nil;
//    self.agencyList=nil;
//    self.imageView=nil;
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title=@"";
    self.agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i<self.agencyList.count; i++) {
        [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
    }
    [self.navigationController setNavigationBarHidden:YES];
    [self updateViewController];
    
    
}

- (void) updateViewController
{
    if(self.agencySection)
    {
        [self.agencySection.contents removeAllObjects];
        for (int i=0; i<self.agencyList.count; i++) {
            [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
        }
    }
    [self.tableView reloadData];
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=NSLineBreakByWordWrapping;
    cell.textLabel.text=sectionContentString;
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    cell.opaque=NO;    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (indexPath.section==0) {
        return 0;
    }else {
        return 44;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section==0) {
        CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
        UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
        headerView.backgroundColor = [UIColor clearColor];
        UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
        aLabel.text =[[self.sections objectAtIndex:section] header] ;
        aLabel.numberOfLines=0;
        aLabel.lineBreakMode=NSLineBreakByWordWrapping;
        aLabel.font = [UIFont boldSystemFontOfSize:24.0];
        aLabel.textAlignment = NSTextAlignmentLeft;
        aLabel.backgroundColor = [UIColor clearColor];
        aLabel.textColor=[UIColor darkGrayColor];       
        [headerView addSubview:aLabel];
        return headerView;
    }
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = NSTextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkTextColor];
    
    
    [headerView addSubview:aLabel];
    
    if (section==1) {
        UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
        [newbutton setFrame:CGRectMake(120,4,30,30)];
        [newbutton setTag:(section)];
        [newbutton addTarget:self action:@selector(clickAddAgencyButton:)
            forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:newbutton];
    }
    //Then you can add a UILabel to your headerView
    
    
    return headerView;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Commit the delete
        [self removeAgency:indexPath.row];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    
    return [[self.sections objectAtIndex:section] header];
    
}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        int tag=[self publicSender];
        [XMLParser removeAgency:[self.agencyList objectAtIndex:tag]];
        self.agencyList=[XMLParser getAgencyList];
        _agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.agencyList.count; i++) {
            [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
        }
        
        [self.tableView reloadData];
    } else {
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}

#pragma mark - Customized codes
- (void) clickAddTimerGroupButton
{
    
    
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 1:
        {
                        SMRTAgencyViewController *detailViewController=[[[SMRTAgencyViewController alloc] initWithNibNameAndAgency:@"SMRTAgencyViewController" agency:[self.agencyList objectAtIndex:indexPath.row] bundle:nil] autorelease];
            //            //    self.navigationItem.titleView=nil;
            //            //    [self.imageView removeFromSuperview];
                        self.navigationItem.title=@"Home";
                        [detailViewController setTitle:@"Agency"];
                        [self.navigationController pushViewController:detailViewController animated:YES];
        }
            break;
        case 2:
        {
            //            if (!self.gpsRecordViewController) {
            //                self.gpsRecordViewController=[[[GPSRecorderViewController alloc] init] autorelease];
            //            }
            //
            //            self.navigationItem.title=@"Home";
            //            [self.gpsRecordViewController setTitle:@"GPS Tool"];
            //            [self.navigationController pushViewController:self.gpsRecordViewController animated:YES];
        }
            
        default:
            break;
    }
    
    
    //[self.navigationController setNavigationBarHidden:NO animated:YES];
    
    //[[SignalAssistorDetailEditViewController alloc]initWithNibNameTimerGroupIDAndSignalID:@"SignalAssistorDetailEditViewController" timerGroupID:timerGroupIDString signalID:signalIDString bundle:nil] ;
}

#pragma mark - Customized functions
- (void) clickAddAgencyButton:(id)sender
{
    Agency * newAgency=[[[Agency alloc] init] autorelease];
    [newAgency setAgencyID:[XMLParser createAgencyID]];
    [newAgency setAgencyName:@"New Agency"];
    [XMLParser createAgency:newAgency];
    self.agencyList=[XMLParser getAgencyList];
    [self.agencySection.contents removeAllObjects];
    for (int i=0; i<self.agencyList.count; i++) {
        [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
    }
    
    [self.tableView reloadData];
    
}

- (void) removeAgency:(int) row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                    message:@"Delete the agency and its signals?"
                                                   delegate:self
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}


//- (void) goToDataFileSelection:(id)sender
//{
//    XMLFileListViewController *fileListViewController=[[[XMLFileListViewController alloc] initWithNibName:@"XMLFileListViewController" bundle:nil] autorelease];
//    [fileListViewController setTitle:@"XML Data Files"];
//    [self.navigationController pushViewController:fileListViewController animated:YES];
//}

@end
